package com.gym.code.config.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gym.code.config.admin.bean.method.MethodBaseMappingBean;
import com.gym.code.config.admin.bean.method.MethodColumnMappingBaseBean.FunctionMappingType;
import com.gym.code.config.admin.bean.method.MethodColumnMappingBean;
import com.gym.code.config.admin.bean.method.MethodMappingBean;
import com.gym.code.config.admin.dao.IMethodMappingDao;
import com.gym.code.config.admin.service.IMethodColumnMappingService;
import com.gym.code.config.admin.service.IMethodMappingService;

/**
 * 
 * @author xinchun.wang 
   @email: 532002108@qq.com
 * @createTime 2015-4-11 下午4:39:30
 */
@Service
public class MethodMappingService implements IMethodMappingService{

	@Autowired
	private IMethodMappingDao  functionMappingDao;
	
	
	@Autowired
	private IMethodColumnMappingService functionColumnMappingService;
	
	@Override
	public int insert(MethodBaseMappingBean bean) {
		return functionMappingDao.insert(bean);
	}

	@Override
	public MethodBaseMappingBean queryBase(long id) {
		return functionMappingDao.queryBase(id);
	}

	@Override
	public int update(MethodBaseMappingBean bean) {
		return functionMappingDao.update(bean);
	}

	@Override
	public List<MethodBaseMappingBean> queryBaseByTableId(long tableId) {
		return functionMappingDao.queryBaseByTableId(tableId);
	}

	@Override
	public MethodMappingBean query(long id) {
		MethodBaseMappingBean baseBean= queryBase(id);
		return wrapMethodMappingBean(baseBean);
	}

	@Override
	public List<MethodMappingBean> queryByTableId(long tableId) {
		List<MethodMappingBean>  result = new ArrayList<MethodMappingBean>();
		List<MethodBaseMappingBean>  baseList = queryBaseByTableId(tableId);
		for(MethodBaseMappingBean item : baseList){
			result.add(wrapMethodMappingBean(item));
		}
		return result;
	}
	
	
	private MethodMappingBean wrapMethodMappingBean(MethodBaseMappingBean baseBean){
		MethodMappingBean bean = new MethodMappingBean(baseBean);
		List<MethodColumnMappingBean> methodList = functionColumnMappingService.queryByMethodId(baseBean.getId());
		
		List<MethodColumnMappingBean> paramList = new ArrayList<MethodColumnMappingBean>();
		List<MethodColumnMappingBean> resultList = new ArrayList<MethodColumnMappingBean>();
		List<MethodColumnMappingBean> updateList = new ArrayList<MethodColumnMappingBean>();
		for(MethodColumnMappingBean item : methodList){
			if(FunctionMappingType.parameter == item.getMappingType()){
				paramList.add(item);
			} else if(FunctionMappingType.result == item.getMappingType()){
				resultList.add(item);
			}else {
				updateList.add(item);
			}
		}
		
		bean.getParameterList().addAll(paramList);
		bean.getResultList().addAll(resultList);
		bean.getUpdateList().addAll(updateList);
		return bean;
	}
	
}
